package com.hotelvip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotelvip.common.exception.ServiceException;
import com.hotelvip.common.utils.ShiroUtils;
import com.hotelvip.dao.ItemMapper;
import com.hotelvip.dao.ItemTurnMapper;
import com.hotelvip.dao.VItemMapper;
import com.hotelvip.dao.VipCardItemMapper;
import com.hotelvip.dto.ReplaceVitemDTO;
import com.hotelvip.dto.TransferVitemDTO;
import com.hotelvip.entity.Item;
import com.hotelvip.entity.ItemTurn;
import com.hotelvip.entity.VipCardItem;
import com.hotelvip.service.ItemService;
import com.hotelvip.service.ItemTurnService;
import com.hotelvip.vo.ItemVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lzh
 * @date 2020/12/16 11:24
 */
@Service
@Slf4j
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemTurnService itemTurnService;
    @Autowired
    private ItemTurnMapper itemTurnMapper;
    @Autowired
    private VItemMapper vItemMapper;
    @Autowired
    private VipCardItemMapper vipCardItemMapper;

    /**
     * 新增商品
     *
     * @param item
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveItem(@RequestBody Item item) {
        //验证
        if (item.getTitle() == null || item.getTitle() == "") {
            throw new ServiceException("商品名称不能为空");
        }
        log.info("参数验证完成");
        //初始化状态
        if (item.getStatus() == null || item.getStatus() != 1) {
            item.setStatus(3);
        }
        item.setAddPeople(ShiroUtils.getUsername());
        log.info("完成初始化数据");
        //添加数据
        int rows = itemMapper.insert(item);
        if (rows < 1) {
            throw new ServiceException("商品添加失败");
        }
        Long itemId = item.getId();
        Long[] tIds = item.getTIds();
        if (tIds != null && tIds.length != 0) {
            boolean flag = itemTurnService.saveItemTurn(itemId, tIds);
            if (!flag) {
                throw new ServiceException("添加关联失败");
            }
        }
        log.info("数据处理完成");

    }

    /**
     * 根据id查找商品与可置换商品
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ItemVo findItemAndTurnItemById(Long id) {
        //校验
        if (id == null || id <= 0) {
            throw new ServiceException("商品id有误");
        }
        //查询
        Item item = itemMapper.selectById(id);
        if (item == null) {
            throw new ServiceException("商品不存在");
        }
        //查询关联表获取可置换商品id t_id
        Long itemId = item.getId();
        QueryWrapper<ItemTurn> itemTurnQueryWrapper = new QueryWrapper<>();
        itemTurnQueryWrapper.eq("item_id", itemId);
        List<ItemTurn> dbItemTurns = itemTurnMapper.selectList(itemTurnQueryWrapper);
        //创建itemlist对象封装到vo对象中
        List<Item> turnItems = new ArrayList<>();
        for (ItemTurn itemTurn : dbItemTurns) {
            itemMapper.selectById(itemTurn.getItemId());
            turnItems.add(itemMapper.selectById(itemTurn.getItemId()));
        }
        return new ItemVo().setItem(item).setTurnItem(turnItems);
    }

    /**
     * 根据id查商品
     *
     * @param itemId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ItemVo findItemById(Long itemId) {
        //验证
        if (itemId == null || itemId <= 0) {
            throw new ServiceException("商品id有误");
        }
        Item item = itemMapper.selectById(itemId);
        if (item == null) {
            throw new ServiceException("查找的商品不存在");
        }
        return new ItemVo().setItem(item);
    }

    /**
     * 查询商品列表信息
     *
     * @param current
     * @param size
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Page<ItemVo> findAllItems(Integer current, Long size) {
        //验证
        if (current == null || current <= 0) {
            throw new ServiceException("当前页码不合法");
        }
        if (size == null || size <= 1) {
            throw new ServiceException("最大页码值不合法");
        }
        //分页处理
        Page<Item> itemsPage = new Page<>(current, size);
        //获取数据
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.lambda().orderByDesc(Item::getUpdatedTime);
        itemMapper.selectPage(itemsPage, itemQueryWrapper);
        List<Item> items = itemsPage.getRecords();
        //封装
        List<ItemVo> itemVos = new ArrayList<>();
        for (Item item : items) {
            itemVos.add(new ItemVo().setItem(item));
        }
        Page<ItemVo> itemsVoPage = new Page<>(current, size, itemsPage.getTotal());
        itemsVoPage.setRecords(itemVos);
        return itemsVoPage;
    }

    /**
     * 按照id修改对应商品信息
     *
     * @param item
     */
    @Override
    public void updateItemById(Item item) {
        //校验
        if (item.getId() == null || item.getId() <= 0) {
            throw new ServiceException("商品id不合法");
        }
        if (itemMapper.selectById(item.getId()) == null) {
            throw new ServiceException("需要修改的商品不存子啊");
        }
        itemMapper.updateById(item);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteItemByIds(Long[] id) {
        UpdateWrapper<Item> itemUpdateWrapper = new UpdateWrapper<>();
        itemUpdateWrapper.lambda().in(Item::getId, id);
        int delete = itemMapper.delete(itemUpdateWrapper);
        if (delete < 1)
            throw new ServiceException("商品可能已经不存在");
        UpdateWrapper<ItemTurn> itemTurnUpdateWrapper = new UpdateWrapper<>();
        itemTurnUpdateWrapper.lambda().in(ItemTurn::getItemId, id);
        itemTurnMapper.delete(itemTurnUpdateWrapper);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void transferVItem(TransferVitemDTO transferVitemDTO) {
        //参数验证
        if (transferVitemDTO.getEndId() == null || transferVitemDTO.getStartId() == null || transferVitemDTO.getNum() == null) {
            throw new ServiceException("参数错误");
        }
        //调整被置换一方的数量
        int i = vItemMapper.transferVItem(transferVitemDTO.getStartId(), 0 - transferVitemDTO.getNum());
        if (i == 0) {
            throw new ServiceException("被置换方数量不足已提供");
        }
        //调整置换后的一方的数量
        vItemMapper.transferVItem(transferVitemDTO.getEndId(), transferVitemDTO.getNum());
    }

    @Override
    public List<Item> getItemByKey(String key) {
        LambdaQueryWrapper<Item> like = new QueryWrapper<Item>().lambda().like(Item::getTitle, key);
        List<Item> items = itemMapper.selectList(like);
        return items;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void replaceVitem(ReplaceVitemDTO replaceVitemDTO) {
        //验证
        Class aClass = replaceVitemDTO.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            try {
                if (declaredField.get(replaceVitemDTO) == null) {
                    throw new ServiceException("参数不能为空");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new ServiceException("参数获取异常");
            }
        }
        VipCardItem vipCardItem = vipCardItemMapper.selectById(replaceVitemDTO.getStartId());
        LambdaQueryWrapper<VipCardItem> eq = new QueryWrapper<VipCardItem>().lambda()
                .eq(VipCardItem::getVId, vipCardItem.getVId()).eq(VipCardItem::getType, 1);
        List<VipCardItem> vipCardItems = vipCardItemMapper.selectList(eq);
        for (VipCardItem cardItem : vipCardItems) {
            //减少旧的产品
            if (cardItem.getId().equals(replaceVitemDTO.getStartId())) {
                if (cardItem.getTotal() - replaceVitemDTO.getNum().intValue() < 0 || cardItem.getUsable() - replaceVitemDTO.getNum().intValue() < 0)
                    throw new ServiceException("所拥有商品数量不足置换");
                VipCardItem tempCardItem = new VipCardItem();
                tempCardItem.setTotal(cardItem.getTotal() - replaceVitemDTO.getNum().intValue())
                        .setUsable(cardItem.getUsable() - replaceVitemDTO.getNum().intValue())
                        .setId(cardItem.getId());
                vipCardItemMapper.updateById(tempCardItem);
                //如果用户所有的卡片中已有被置换商品 则在基础上添加
                Boolean flag = false;
                VipCardItem vipCardItemId = null;
                for (VipCardItem item : vipCardItems) {
                    if (item.getItemId().equals(replaceVitemDTO.getItemId())) {
                        flag = true;
                        vipCardItemId = item;
                        break;
                    }
                }
                if (flag) {
                    VipCardItem tempCardItem1 = new VipCardItem();
                    tempCardItem1.setTotal(vipCardItemId.getTotal() + replaceVitemDTO.getItemNum().intValue())
                            .setUsable(vipCardItemId.getUsable() + replaceVitemDTO.getItemNum().intValue())
                            .setId(vipCardItemId.getId());
                    vipCardItemMapper.updateById(tempCardItem1);
                } else {
                    Item item = itemMapper.selectById(replaceVitemDTO.getItemId());
                    VipCardItem saveVipCardItem = new VipCardItem();
                    saveVipCardItem.setVId(cardItem.getVId())
                            .setItemNum(replaceVitemDTO.getItemNum().intValue())
                            .setTotal(replaceVitemDTO.getItemNum().intValue())
                            .setUsable(replaceVitemDTO.getItemNum().intValue())
                            .setType(1)
                            .setItemId(replaceVitemDTO.getItemId())
                            .setItemTitle(item.getTitle() != null ? item.getTitle() : null)
                            .setItemImage(item.getImage() != null ? item.getImage() : null)
                            .setItemPrice(item.getPrice() != null ? item.getPrice() : null)
                            .setItemUnit(item.getUnit() != null ? item.getUnit() : null);
                    vipCardItemMapper.insert(saveVipCardItem);
                }
            }


        }

    }
}
